<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/header.jsp" %>

 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="${ctx}/assets/js/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="${ctx}/assets/js/ztree/js/ztree.js"></script>
    <script type="text/javascript" src="${ctx}/assets/js/ztree/js/jquery.ztree.core-3.5.js"></script> 
    <script type="text/javascript">
    var JPos = {};
    (function($){
    	$.$getAbsPos = function(p){
    		var _x = 0;
    		var _y = 0;
    		while(p.offsetParent){
    				_x += p.offsetLeft;
    				_y += p.offsetTop;
    				p = p.offsetParent;
    		}
    		
    		_x += p.offsetLeft;
    		_y += p.offsetTop;
    		
    		return {x:_x,y:_y};
    	};
    	
    	$.$getMousePos = function(evt){
    		var _x,_y;
    		evt = evt || window.event;
    		if(evt.pageX || evt.pageY){
    			_x = evt.pageX;
    			_y = evt.pageY;
    		}else if(evt.clientX || evt.clientY){
    			_x = evt.clientX + document.body.scrollLeft - document.body.clientLeft;
    			_y = evt.clientY + document.body.scrollTop - document.body.clientTop;
    		}else{
    			return $.$getAbsPos(evt.target);	
    		}
    		return {x:_x,y:_y};
    	}
    })(JPos);

    function vControl(pChoice){
    	////debugger;
    	switch(pChoice){
    		case "GETMOUSEPOSINPIC":
    			var mPos = JPos.$getMousePos();
    			var iPos = JPos.$getAbsPos(arguments[1]);
    			
    			window.status = (mPos.x - iPos.x) + " " + (mPos.y - iPos.y);
    			var rightclickPoint = {lnt:(mPos.x - iPos.x + 5),lat:(mPos.y - iPos.y + 40)};
    			return rightclickPoint;
    			break;
    	}
    }

    </script>
      
    <SCRIPT type="text/javascript">
    var result = $.parseJSON('${jsonArray}');
    var checkType ='${checkType}';
    var zTree, uMenu;
    var setting = {
    	data: {
    		simpleData: {
    			enable: true
    		}
    	},
    	edit:{
    		enable: true,
    		showRemoveBtn: false,
    		showRenameBtn: false
    	},
    	view: {
    		dblClickExpand: false
    	},
    	check: {
    		enable: true
    	},
    	callback: {
    		onRightClick: OnRightClick,
    		onClick: onClick
    	} ,
    	async: {
    		enable: true,
    		url:"${ctx}/org/haveChildNodes?isCheckOrg=0",
    		autoParam:["id","messageType","checkType"],
    		type: "post",
    		dataType: "json",
    		dataFilter: filter
    	} 
    };
    	
    function filter(treeId, parentNode, childNodes) {
    	//debugger;
    	var treeNodes = childNodes[0];
    	//alert(treeNodes);
    	if(childNodes.length < 1) {
    		zTree.removeChildNodes(parentNode);
    	} else {
    		return resultToNodes(childNodes);
    	}
    }
  //兼容火狐版本，增加全局变量window.event
    if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){  
    	var $E = function(){var c=$E.caller; while(c.caller)c=c.caller; return c.arguments[0]};
        __defineGetter__("event", $E);
    }
     function onClick(event, treeId, treeNode) {
    	//debugger;
    	var param;
    	if(treeNode.messageType == "dept"){
			param= {"deptId":treeNode.id};
	 	}else if(treeNode.messageType == "org"){
	 		param= {"orgId":treeNode.id};
	    	$("#selectOrgId").val(treeNode.id);
	 	}
    	$("#selectOrgOrDeptFlag").data("orgData",param);
    	 
		$("#userListDiv").show();
		$("#userListDiv").load("${ctx}/user/list",param );
		
    } 


    function OnRightClick(event, treeId, treeNode) {
    	if(treeNode == null){
    		return null;
    	}
    	var position = vControl('GETMOUSEPOSINPIC',$("#user_tree").get(0));
    	if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
    		zTree.cancelSelectedNode();
    		showRMenu(treeNode,  position.lnt, position.lat);
    	} else if (treeNode && !treeNode.noR) {
    		var scrollTop1 = $("#user_tree").find("div").first().scrollTop();
    		var scrollTop2 = document.documentElement.scrollTop || $("body").scrollTop();
    		zTree.selectNode(treeNode);
    		var _scrollTop1 = $("#user_tree").find("div").first().scrollTop();
    		var _scrollTop2 = document.documentElement.scrollTop || $("body").scrollTop();
    		//排除360急速模式与IE11版本中出现滚动条跳动问题
    		//实现方法：记录跳动之前的滚动条位置，判断跳动之后，滚动条位置是否发生了改变，如果发生改变了，则还原回来
    		if(scrollTop1 != _scrollTop1 || scrollTop2 != _scrollTop2){
    			$("#user_tree").find("div").first().scrollTop(scrollTop1);
    			document.documentElement.scrollTop = scrollTop2;
    			$("body").scrollTop(scrollTop2);
    		}
    	//	var scrollTop = $("#user_tree").find("div").first().scrollTop();
    		//alert(document.documentElement.scrollTop);
    		//zTree.selectNode(treeNode);
    		if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)
			showRMenu(treeNode, position.lnt, position.lat);
    		else showRMenu(treeNode, position.lnt, position.lat + document.documentElement.scrollTop);
    		///showRMenu(treeNode, position.lnt, position.lat);
    	 }
    }
    function showRMenu(node, x, y) {
        $("#addUserDiv ul").show();
        //if (node.messageType=="dept") {
        if (node.messageType=="org") {
            $("#addUser").show();
        } else {
           return null;
        }
        uMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }
    function hideRMenu() {
    	if (uMenu) uMenu.css({"visibility": "hidden"});
    	$("body").unbind("mousedown", onBodyMouseDown);
    }
    function onBodyMouseDown(event){
    	if (!(event.target.id == "addUserDiv" || $(event.target).parents("#addUserDiv").length>0)) {
    		uMenu.css({"visibility" : "hidden"});
    	}
    }

     var orgO = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/org.png", 
        orgC = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/org.png", 
        org = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/org.png", 
        dept = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/dept.png";
     
        //分割子节点
        function resultToNodes(result){
          	//debugger;
          	var fNodes = [];
         		$.each(result,function(i,node){
         			fNodes.push(getNodes(node,checkType));
         		});
          	return fNodes;
        }
        //设置子节点信息
          function getNodes(node,checkType){
          	var fNode = {
          		id: node.id, //节点编号
          		pId: node.pId, //父节点编号
          		name:node.text,//节点名称（在机构树上展示的名称）
          		open:node.isOpen==1?true:false, //是否打开子节点
          		messageType: node.nodeType, //节点属性（自定义），分org/dept
          		status:node.status, //状态，0-未启用 1-启用 2-停用
          		isParent: node.hasChild==1?true:false,//是否含有子节点
          		type:node.type,//机构节点专用类型 1-机构 0-部门
          		checkType: checkType,//机构树类型 分org(只展示机构)/dept(展示机构、部门)/user(展示机构、部门、人员)
          		iconOpen: orgO, //节点图标
          		iconClose: orgC,//节点图标
          		icon: org, // 节点图标
          	};
          	if(node.type == "item") {
          		fNode.iconOpen = dept;
          		fNode.iconClose = dept;
          		fNode.icon = dept; 
          	} 
          	return fNode;
          }
          //检查节点状态，如果为非启用状态，则不允许添加子节点
            function checkStatus(zNodes) {
            	var z = zNodes==null?zTree.getSelectedNodes()[0]:zNodes;
            	if(z.status != "1") {
            		alert("该" + (z.messageType=="org"?"机构":"部门") + "为非启用或停用状态,不能增加人员"); //+ (z.checkType=="user"?"人员":"子部门") + "!");
            		return false;
            	}
            	return true;
            }
          //页面加载树结构
                var scripts = [null, null];
                $('.page-content-area').ace_ajax('loadScripts', scripts, function() {
                $.fn.zTree.init($("#userTree"), setting, resultToNodes(result));
            	zTree = $.fn.zTree.getZTreeObj("userTree");
            	uMenu = $("#addUserDiv");
            });
            function addUser(str){
            	var zNodes =zTree.getSelectedNodes()[0];
            	if(!checkStatus()) return;	
            	$("#userInfoDiv").show();
            	var param = "";
            	if(str.id =="addUser"){
            		//param={"deptId":zNodes.id};
            		param={"orgId":zNodes.id};
            		$('#userInfoDiv').load("${ctx}/user/toInsert.do",param,function(){
            			$("#userInfoDiv").data("userBtnFlag","add").dialog("open");
            		});
            		
            	}
            	uMenu.css({"visibility" : "hidden"});
            	
            } 
    </script>
    <style type="text/css">
        .ztree li span.button.switch.level0 {visibility:hidden; width:1px;}
        .ztree li ul.level0 {padding:0; background:none;}
    </style>
    <style type="text/css">
        div#addUserDiv {
        position:absolute; 
        visibility:hidden; 
        top:0; 
        background-color: #fff;
        text-align: center;
        padding: 1px;
        }
        div#addUserDiv ul li{
            margin: 1px 0;
            padding: 0 5px;
            cursor: pointer;
            list-style: none outside none;
            background-color: #fff;
        }
    </style> 
<div class="row">
	<div class="col-xs-12">
		<!-- PAGE CONTENT BEGINS -->

		<!-- #section:plugins/fuelux.treeview -->
		<div class="row">
			<div class="col-sm-12">
				<div class="widget-box widget-color-blue2">				
					<div class="widget-header">
						<h4 class="widget-title lighter smaller"><hw:orgName orgId="${rootOrgId}" />(${rootOrgId})</h4>
						<!-- #section:custom/widget-box.toolbar -->
						<div class="widget-toolbar">
							<a href="#" data-action="fullscreen" class="orange2"><i class="ace-icon fa fa-expand"></i></a>
							<a href="#" data-action="close"><i class="ace-icon fa fa-times"></i></a>
						</div>
						<!-- /section:custom/widget-box.toolbar -->
					</div>
					<div class="widget-body" id="user_tree" >
						<div class="widget-main padding-8" style="height:800px;overflow:auto;" >
							<ul id="userTree"  class="ztree"></ul>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div><!-- /.col -->
</div><!-- /.row -->

<div id="addUserDiv" style="position:absolute;">
  	<ul class="dropdown-menu" role="menu">
       <li><a tabindex="-1" class="grey" id="addUser" onclick="addUser(this);"><i class='ace-icon fa fa-user blue'></i>新增用户</a></li>
  	</ul>
</div>

<!-- #dialog-message -->
<div id="dialog-message">
</div>


